package com.wyclabs.auth.common;

import com.wyclabs.commons.response.UserResponse;
import com.wyclabs.commons.utils.BeanUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义 UserDetails
 * @author sr
 * @date 2019/10/17
 */
@Data
@NoArgsConstructor
public class SecurityUser implements UserDetails, Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty("是否可用")
    private Boolean enable;

    @ApiModelProperty("登录用户名")
    private String userName;

    @ApiModelProperty("密码")
    private String password;

    @ApiModelProperty("角色列表")
    private List<String> roleList = new ArrayList<>();

    @ApiModelProperty("平台类型")
    private String platFormType;

    public SecurityUser(UserResponse userResponse) {
        BeanUtils.copyProperties(userResponse, this);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (String role : roleList) {
            authorityList.add(new SimpleGrantedAuthority(role));
        }
        return authorityList;
    }

    /**
     * Returns the password used to authenticate the user.
     * @return the password
     */
    @Override
    public String getPassword() {
        return password;
    }

    /**
     * Returns the username used to authenticate the user. Cannot return <code>null</code>.
     * @return the username (never <code>null</code>)
     */
    @Override
    public String getUsername() {
        return userName;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * Indicates whether the user is enabled or disabled. A disabled user cannot be
     * authenticated.
     * @return <code>true</code> if the user is enabled, <code>false</code> otherwise
     */
    @Override
    public boolean isEnabled() {
        return enable;
    }

}
